package cn.iocoder.yudao.module.member.service.activation;

import cn.iocoder.yudao.module.member.controller.admin.activation.vo.ActivationPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.activation.vo.ActivationSaveReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.activation.ActivationDO;
import cn.iocoder.yudao.module.member.dal.mysql.activation.ActivationMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.ACTIVATION_EXISTS;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.ACTIVATION_NOT_EXISTS;

/**
 * 激活码管理 Service 实现类
 *
 * @author Alan
 */
@Service
@Validated
public class ActivationServiceImpl implements ActivationService {

    @Resource
    private ActivationMapper activationMapper;

    @Override
    public Long createActivation(ActivationSaveReqVO createReqVO) {
        ActivationDO activationDO = activationMapper.selectOne(new LambdaQueryWrapper<ActivationDO>()
                .eq(ActivationDO::getActivationCode, createReqVO.getActivationCode()));
        if (Objects.nonNull(activationDO)){
            throw exception(ACTIVATION_EXISTS);
        }
        // 插入
        ActivationDO activation = BeanUtils.toBean(createReqVO, ActivationDO.class);
        activationMapper.insert(activation);
        // 返回
        return activation.getId();
    }

    @Override
    public void updateActivation(ActivationSaveReqVO updateReqVO) {
        // 校验存在
        validateActivationExists(updateReqVO.getId());
        // 更新
        ActivationDO updateObj = BeanUtils.toBean(updateReqVO, ActivationDO.class);
        activationMapper.updateById(updateObj);
    }

    @Override
    public void deleteActivation(Long id) {
        // 校验存在
        validateActivationExists(id);
        // 删除
        activationMapper.deleteById(id);
    }

    private void validateActivationExists(Long id) {
        if (activationMapper.selectById(id) == null) {
            throw exception(ACTIVATION_NOT_EXISTS);
        }
    }

    @Override
    public ActivationDO getActivation(Long id) {
        return activationMapper.selectById(id);
    }

    @Override
    public PageResult<ActivationDO> getActivationPage(ActivationPageReqVO pageReqVO) {
        return activationMapper.selectPage(pageReqVO);
    }

}